/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import Vo.User;

/**
 *
 * @author Mayiyaheila
 */
public class UserDao {
	private Connection conn = null;
	public void initConnection() throws Exception {
		//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		Class.forName("com.mysql.cj.jdbc.Driver");
		//conn = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=school", "sa", "123456");
		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/forum", "root", "root");
	}

	public User getUserByAccount(String account) throws Exception {
		User user = null;
		initConnection();
		String sql = "SELECT Uid,password,username,pic FROM user WHERE Uid=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, account);
		ResultSet rs = ps.executeQuery();

		System.out.println("ResultSet: " + rs.toString());
		if (rs.next()) {
			user = new User();
			user.setUid(rs.getString("Uid"));
			user.setPassword(rs.getString("password"));
			user.setUsername(rs.getString("username"));
			user.setPic(rs.getString("pic"));
		}
		closeConnection();
		return user;
	}

	public boolean register(String uid, String password, String username) throws Exception {
		boolean flag = false;
		PreparedStatement pstmt = null;
		initConnection();
		String sql = "INSERT INTO user(Uid,username,password,pic) VALUES (?,?,?,'0.jpg')";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, uid);
		pstmt.setString(2, username);
		pstmt.setString(3, password);
		if (pstmt.executeUpdate() > 0) {
			flag = true;
		}
		closeConnection();
		return flag;
	}

	public boolean changer(String uid, String password, String pic) throws Exception {
		boolean flag = false;
		PreparedStatement pstmt = null;
		initConnection();
		String sql = "update user set password=?,pic=? where uid=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, password);
		pstmt.setString(2, pic);
		pstmt.setString(3, uid);
		if (pstmt.executeUpdate() > 0) {
			flag = true;
		}
		closeConnection();
		return flag;
	}
	public void closeConnection() throws Exception {
		conn.close();
	}

}